package com.ztstkj.lzservices.mmkvs

import android.content.Context
import com.tencent.mmkv.MMKV

class MmkvUtil private constructor(){

    lateinit var mmKv: MMKV
    companion object {
        const val DATE_FORMAT = "yyyy-MM-dd HH.mm.ss"
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { MmkvUtil() }
    }
    fun init(context: Context) {
        //第一种使用mmkv默认目录
        MMKV.initialize(context)
        mmKv = MMKV.mmkvWithID("app-scale-k", MMKV.MULTI_PROCESS_MODE)
    }

    fun remove(key: String){
        mmKv.remove(key)
    }
    fun encode(key: String, value: Any) {
        when (value) {
            is String -> mmKv.encode(key, value)
            is Int -> mmKv.encode(key, value)
            is Boolean -> mmKv.encode(key, value)
            is Long -> mmKv.encode(key, value)
            is Float -> mmKv.encode(key, value)
            is Double -> mmKv.encode(key, value)
        }
    }

    inline fun <reified T> decode(key: String, defaultValue: T): T = when (T::class) {
        String::class -> mmKv.decodeString(key, defaultValue as String?) as T
        Int::class -> mmKv.decodeInt(key, defaultValue as Int) as T
        Boolean::class -> mmKv.decodeBool(key, defaultValue as Boolean) as T
        Long::class -> mmKv.decodeLong(key, defaultValue as Long) as T
        Float::class -> mmKv.decodeFloat(key, defaultValue as Float) as T
        Double::class -> mmKv.decodeDouble(key, defaultValue as Double) as T
        else -> throw IllegalArgumentException("Unsupported type")
    }
}